<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import OrderItem from './OrderItem.vue';
import { listPointRecord } from '@/api/pointRecord/pointRecord.js';

const orderList = ref([[], [], [], [], []]);
const list = reactive([
	{ name: '待发货', status: '1' },
	{ name: '已发货', status: '2' },
	{ name: '已完成', status: '3' },
	{ name: '已取消', status: '4' },
	{ name: '已退回', status: '5' }
]);
const current = ref(0);
const swiperCurrent = ref(0);
const loadStatus = ref(['loadmore', 'loadmore', 'loadmore', 'loadmore', 'loadmore']);
const pages = ref([
	{ pageNum: 1, pageSize: 10 },
	{ pageNum: 1, pageSize: 10 },
	{ pageNum: 1, pageSize: 10 },
	{ pageNum: 1, pageSize: 10 },
	{ pageNum: 1, pageSize: 10 }
]);

// 添加一个标记来防止重复加载
const isFirstLoad = ref(true);

onMounted(() => {
	// 首次加载当前标签页的数据
	if (orderList.value[current.value].length === 0) {
		getOrderList(current.value);
	}
});

onShow(() => {
	// 页面显示时刷新当前标签页的数据，但避免首次重复加载
	if (!isFirstLoad.value) {
		refreshCurrentTabData();
	} else {
		isFirstLoad.value = false;
	}
});

// 触底懒加载
const reachBottom = () => {
	const i = current.value;
	if (loadStatus.value[i] === 'nomore' || loadStatus.value[i] === 'loading') {
		return;
	}
	getOrderList(i);
};

// 去重函数
const removeDuplicates = (arr) => {
	const seen = new Set();
	return arr.filter(item => {
		const duplicate = seen.has(item.id);
		seen.add(item.id);
		return !duplicate;
	});
};

// 页面数据
const getOrderList = async (idx) => {
	const currentPage = pages.value[idx];
	if (loadStatus.value[idx] === 'nomore') {
		return;
	}
	loadStatus.value.splice(idx, 1, "loading");
	try {
		const res = await listPointRecord({
			exchangeStatus: list[idx].status,
			pageNum: currentPage.pageNum,
			pageSize: currentPage.pageSize
		});

		const records = (res.rows || res.data || []).map(item => {
			// 计算单价：总积分消耗除以数量
			const unitPrice = item.exchangeQuantity > 0 ? Math.floor(item.pointsCost / item.exchangeQuantity) : item.pointsCost;

			return {
				id: item.id,
				store: '积分商城',
				deal: list[idx].name,
				totalPoints: item.pointsCost, // 添加总积分字段
				goodsList: [
					{
						goodsUrl: item.productImage || '',
						title: item.productName,
						type: item.remark || '默认',
						deliveryTime: item.exchangeTime,
						price: String(unitPrice), // 存储单价而不是总价
						number: item.exchangeQuantity || 1
					}
				]
			}
		});

		// 添加新数据前先进行去重
		const existingData = orderList.value[idx];
		const newData = [...existingData, ...records];
		const uniqueData = removeDuplicates(newData);

		orderList.value[idx] = uniqueData;
		currentPage.pageNum++;

		if (records.length < currentPage.pageSize) {
			loadStatus.value.splice(idx, 1, "nomore");
		} else {
			loadStatus.value.splice(idx, 1, "loadmore");
		}
	} catch (e) {
		loadStatus.value.splice(idx, 1, 'loadmore');
		console.error('获取订单列表失败:', e);
	}
};

// 刷新当前标签页数据
const refreshCurrentTabData = () => {
	const i = current.value;
	orderList.value[i] = [];
	pages.value[i].pageNum = 1;
	loadStatus.value.splice(i, 1, "loadmore");
	getOrderList(i);
}

// tab栏切换
const change = ({ index }) => {
	current.value = index; // 更新current变量
	swiperCurrent.value = index;
	if (orderList.value[index].length === 0) {
		getOrderList(index);
	}
};

const animationfinish = (e) => {
	const currentIndex = e.detail.current;
	swiperCurrent.value = currentIndex;
	current.value = currentIndex;
	if (orderList.value[currentIndex].length === 0) {
		getOrderList(currentIndex);
	}
};

// 获取tabs组件的ref
const tabs = ref(null);

const goToMall = () => {
	uni.navigateTo({
		url: '/pages/mallMenu/index1'
	});
};
</script>

<template>
	<view>
		<view class="wrap">
			<view class="u-tabs-box">
				<u-tabs activeColor="#f29100" ref="tabs" :list="list" :current="current" @change="change"
					:is-scroll="false" swiperWidth="750"></u-tabs>
			</view>
			<swiper class="swiper-box" :current="swiperCurrent" @animationfinish="animationfinish">
				<swiper-item class="swiper-item" v-for="(orderlist, index) in orderList" :key="index">
					<scroll-view scroll-y style="height: 100%;width: 100%;" @scrolltolower="reachBottom"
						v-if="orderlist.length !== 0">
						<view class="page-box">
							<OrderItem v-for="res in orderlist" :key="res.id" :order="res" />
							<u-loadmore :status="loadStatus[current]" bgColor="#f2f2f2"></u-loadmore>
						</view>
					</scroll-view>
					<scroll-view scroll-y style="height: 100%;width: 100%;" v-else>
						<view class="page-box">
							<view class="centre">
								<image src="https://cdn.uviewui.com/uview/template/taobao-order.png" mode="aspectFit" class="empty-image">
								</image>
								<view class="explain">
									您还没有相关的订单
									<view class="tips">可以去看看有那些想买的</view>
								</view>
								<view class="btn" @click="goToMall">随便逛逛</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>
<style>
/* #ifndef H5 */
page {
	height: 100%;
	background-color: #f2f2f2;
}

/* #endif */
</style>

<style lang="scss" scoped>
.centre {
	text-align: center;
	margin: 200rpx auto;
	font-size: 32rpx;
	width: 100%;

	.empty-image {
		width: 164rpx;
		height: 164rpx;
		border-radius: 50%;
		margin: 0 auto 20rpx;
		display: block; /* 确保图片作为块级元素 */
	}

	.tips {
		font-size: 24rpx;
		color: #999999;
		margin-top: 20rpx;
	}

	.btn {
		margin: 80rpx auto;
		width: 200rpx;
		border-radius: 32rpx;
		line-height: 64rpx;
		color: #ffffff;
		font-size: 26rpx;
		background: linear-gradient(270deg, rgba(249, 116, 90, 1) 0%, rgba(255, 158, 1, 1) 100%);
	}
}

.wrap {
	display: flex;
	flex-direction: column;
	height: calc(100vh - var(--window-top));
	width: 100%;
}

.swiper-box {
	flex: 1;
}

.swiper-item {
	height: 100%;
}
</style>
